package org.base.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 文本工具类
 */
@Slf4j
public class TextUtils {

    private static TextTokenParser $TOKEN_PARSER = new TextTokenParser("${", "}");

    /**
     * 解析占位符参数
     *
     * @param text
     * @param tokenHandler
     */
    public static String parseText(String text, TextTokenHandler tokenHandler) {
        return $TOKEN_PARSER.parse(text, tokenHandler);
    }

    public static String parseText(String text, Map<String, String> paramMap) {
        if (paramMap == null || paramMap.isEmpty()) {
            return text;
        }
        return $TOKEN_PARSER.parse(text, e -> paramMap.get(e));
    }

    public static String parseText(String text, Object object) {
        if (object == null) {
            return text;
        }
        final Class<?> clazz = object.getClass();
        return $TOKEN_PARSER.parse(text, e -> {
            final Field field = ReflectionUtils.findField(clazz, e);
            if (field != null) {
                field.setAccessible(true);
                try {
                    return (String)field.get(object);
                } catch (IllegalAccessException ex) {
                    log.warn(ex.getMessage(), ex);
                }
            }
            return null;
        });
    }

    public static void main(String[] args) {
        String text = "你好 ${userName} ";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("userName", "张三");
        System.out.println(parseText(text, paramMap));
    }

}
